package com.tyun.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * Druid配置
 *
 * @author congcong tao
 * @date 2017/12/15 12:01
 */
@Configuration
@EnableConfigurationProperties(MybatisProperties.class)
public class DruidConfig {
    private Logger logger = LoggerFactory.getLogger(DruidConfig.class);

    @Autowired
    private MybatisProperties mybatisProperties;

    @Bean(destroyMethod = "close")
    @Primary
    public DataSource dataSource(){
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(mybatisProperties.getUrl());
        datasource.setUsername(mybatisProperties.getUsername());
        datasource.setPassword(mybatisProperties.getPassword());
        datasource.setDriverClassName(mybatisProperties.getDriverClass());
        if (mybatisProperties.getInitialSize() > 0) {
            datasource.setInitialSize(mybatisProperties.getInitialSize());
        }
        if (mybatisProperties.getMinIdle() > 0) {
            datasource.setMinIdle(mybatisProperties.getMinIdle());
        }
        if (mybatisProperties.getMaxActive() > 0) {
            datasource.setMaxActive(mybatisProperties.getMaxActive());
        }
        datasource.setTestOnBorrow(mybatisProperties.isTestOnBorrow());
        try {
            datasource.setFilters(mybatisProperties.getFilters());
            datasource.init();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return datasource;
    }
}
